package com.weiyuanstudio.nextstep.algorithm.snowflake;

import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Snowflake ID Generator
 */
@Slf4j
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Component
public class SnowflakeGenerator implements IdentifierGenerator {
    private static final short SINGLETON_WORKER_ID = 1; //Just for single node server
    SnowflakeGenerator() {
        log.debug("SnowflakeGenerator Init");
        IdGeneratorOptions options = new IdGeneratorOptions(SINGLETON_WORKER_ID);
        YitIdHelper.setIdGenerator(options);
    }

    public long generateId() {
        return YitIdHelper.nextId();
    }

    @Override
    public Long generate(SharedSessionContractImplementor session, Object object) {
        return YitIdHelper.nextId();
    }
}
